package com.menglei.dailytasks.m0715;

import android.Manifest;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.menglei.dailytasks.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class VideoViewActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnPreparedListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnCompletionListener {

    private VideoView mVideoView;
    private ImageView mIvPre;
    private ImageView mIvPlayOrPause;
    private ImageView mIvNext;
    private LinearLayout mActivityMain;
    private MediaController mMediaController;
    private List<Video> mList = new ArrayList<>();
    private int mCurrentIndex = 0;

    //自定义进度条
    private TextView mTvStart;
    private SeekBar mSeekBar;
    private TextView mTvEnd;
    private TextView mTvTitle;
    //
    private int duration;//整个视频的长度
    private int current;//当前进度
    private boolean state = false;//true为播放，false暂停

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_view);
        getVideos();
        initView();

    }

    private void initView() {
        mVideoView = (VideoView) findViewById(R.id.videoView);
        mIvPre = (ImageView) findViewById(R.id.iv_pre);
        mIvPre.setOnClickListener(this);
        mIvPlayOrPause = (ImageView) findViewById(R.id.iv_play_or_pause);
        mIvPlayOrPause.setOnClickListener(this);
        mIvNext = (ImageView) findViewById(R.id.iv_next);
        mIvNext.setOnClickListener(this);
        mActivityMain = (LinearLayout) findViewById(R.id.activity_main);
        mTvStart = (TextView) findViewById(R.id.tv_start);
        mSeekBar = (SeekBar) findViewById(R.id.seekBar);
        mTvEnd = (TextView) findViewById(R.id.tv_end);
        mActivityMain.setOnClickListener(this);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mVideoView.setVideoPath(mList.get(0).getPath());
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnCompletionListener(this);
        mSeekBar.setOnSeekBarChangeListener(this);

    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mSeekBar.setMax(mVideoView.getDuration());
        Log.i("TAGg", "" + mVideoView.getDuration());
        mTvTitle.setText(mList.get(mCurrentIndex).getName());
        mTvEnd.setText(getFormatTime(mVideoView.getDuration()));
        current = 0;
        duration = mVideoView.getDuration();
        new progressAsync().execute();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mIvPlayOrPause.setSelected(false);

    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            if (current == duration) {
                mVideoView.start();
                mIvPlayOrPause.setSelected(true);
                new progressAsync().execute();
            }
            current = progress;
            mVideoView.seekTo(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    private void getVideos() {
        int i = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (i < 0) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        String[] projection = {MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DATA};
        String orderBy = MediaStore.Video.Media.DISPLAY_NAME;
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        getContentProvider(uri, projection, orderBy);
    }

    public void getContentProvider(Uri uri, String[] projection, String orderBy) {
        List<HashMap<String, String>> listImage = new ArrayList<HashMap<String, String>>();
        Cursor cursor = getContentResolver().query(uri, projection, null,
                null, orderBy);
        if (null == cursor) {
            return;
        }
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media._ID));
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
            // Uri parse = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.cloud);
            mList.add(new Video(id, name, path));
        }
    }

    //获取下一首的视频
    public Video getNextVideo() {
        if (mCurrentIndex == mList.size() - 1) {
            mCurrentIndex = 0;
            Toast.makeText(this, "最后一个视频，为您跳转到第一个视频..", Toast.LENGTH_SHORT).show();
        } else {
            mCurrentIndex++;
        }
        return mList.get(mCurrentIndex);
    }

    //获取上一首的视频
    public Video getPreVideo() {
        if (mCurrentIndex == 0) {
            mCurrentIndex = mList.size() - 1;
            Toast.makeText(this, "第一个视频，为您跳转到最后一个视频..", Toast.LENGTH_SHORT).show();
        } else {
            mCurrentIndex--;
        }
        return mList.get(mCurrentIndex);
    }

    //播放还是暂停
    private void playOrPause() {
        if (mVideoView.isPlaying()) {
            Log.i("TAGg", "当前播放 点击暂停");
            //当前处于播放，点击后变成暂停
            mVideoView.pause();
            mIvPlayOrPause.setSelected(false);
            state = false;
        } else {
            if (current == duration) {
                //播放完了，再次点击按钮
                mVideoView.start();
                current = 0;
                duration = mVideoView.getDuration();
                new progressAsync().execute();
                Log.i("TAGg", "播放完了，再次点击按钮");
            } else {
                Log.i("TAGg", "当前暂停 点击继续播放");
                mVideoView.start();
                mIvPlayOrPause.setSelected(true);
                state = true;
            }

        }
    }


    private String getFormatTime(int time) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss");
        return dateFormat.format(new Date(time));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.iv_pre:
                mVideoView.setVideoPath(getPreVideo().getPath());
                mVideoView.start();
                mIvPlayOrPause.setSelected(true);
                break;
            case R.id.iv_play_or_pause:
                playOrPause();
                break;
            case R.id.iv_next:
                mVideoView.setVideoPath(getNextVideo().getPath());
                mVideoView.start();
                mIvPlayOrPause.setSelected(true);
                break;
            case R.id.activity_main:
                break;
        }
    }

    private class progressAsync extends AsyncTask<Void, Integer, Void> {


        @Override
        protected Void doInBackground(Void... params) {
            do {
                Log.i("handleMessage", "" + current);
                try {
                    publishProgress(current);
                    //这里的参数类型是 AsyncTask<Void, Integer, Void>中的Integer决定的，
                    // 在onProgressUpdate中可以得到这个值去更新UI主线程，这里是异步线程
                    Thread.sleep(16);
                    if (state) {
                        current += 16;
                    }

                } catch (Exception e) {
                }
            } while (current <= duration);
            current = duration;
            return null;
        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mTvStart.setText(getFormatTime(values[0]));
            mSeekBar.setProgress(values[0]);
        }
    }

}